<template>
  <div class="home">
    <!-- 导航栏 -->
    <van-nav-bar fixed>
      <van-button
        class="search-button"
        slot="title"
        round
        type="info"
        size="mini"
        @click="$router.push('/search')"
      >搜索
      </van-button>
    </van-nav-bar>
    <!-- 导航栏 -->

    <!-- 频道列表 -->
    <van-tabs v-model="active">

      <van-icon slot="nav-right" name="wap-nav" @click="isChannelShow = true"/>

      <van-tab
      v-for="(item) in channels"
      :key="item.id"
      :title="item.name">
        <!--
          文章列表
          van-pull-refresh 下拉刷新功能
          van-list 列表，带有上拉加载更多功能
        -->
        <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
          <van-list
            v-model="loading"
            :finished="item.finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <van-cell
              v-for="cellItem in item.articles"
              :key="cellItem.art_id.toString()"
              :title="cellItem.title"
              @click="$router.push(`/article/${cellItem.art_id}`)"
               />
          </van-list>
        </van-pull-refresh>
        <!-- /文章列表 -->
      </van-tab>
    </van-tabs>
    <!-- /频道列表 -->
    <!--频道管理弹窗 -->
    <!--
      弹窗组件
      v-model="show" 控制是否展示
      round 圆角
      position="bottom" 弹出位置
      :style="{ height: '20%' }" 弹出高度
    -->
    <van-popup
      v-model="isChannelShow"
      round
      position="bottom"
      closeable
      close-icon-position="top-left"
      :style="{ height: '95%' }"
      @open="openChangeOpen"
    >
      <div class="channel-container">
        <van-cell title="我的频道" :border="false">
          <van-button type="danger" size="mini" @click="isEditShow = !isEditShow">
            {{isEditShow?"完成":"编辑"}}
          </van-button>
        </van-cell>
        <van-grid :gutter="10">
          <van-grid-item
          v-for="(channel,index) in channels"
          :key="channel.id"
          :text="channel.name"
          @click="onChannelActiveOrDelete(channel,index)">
            <van-icon v-show="isEditShow"  class="close-icon"  slot="icon"  name="close"  size="20"  />
          </van-grid-item>

        </van-grid>

        <van-cell title="推荐频道" :border="false" />
        <van-grid :gutter="10">
           <van-grid-item
              v-for="channel in recommendChannels"
              :key="channel.id"
              :text="channel.name"
              @click="onChannelAdd(channel)"
            />
        </van-grid>
      </div>
    </van-popup>
    <!-- /频道管理弹窗 -->

  </div>
</template>

<script>
import { getUserChannels } from '@/api/user'
import { getAllChannels } from '@/api/channel'
import { getArticles } from '@/api/article'
import { getItem, setItem } from '@/utils/storage'
export default {
  name: 'HomePage',
  components: {},
  props: {},
  data () {
    return {
      active: 0,
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      channels: [], // 频道列表
      allChannels: [], // 所有频道列表
      isChannelShow: false, // 这里我们先设置为 true 就能看到弹窗的页面了
      isEditShow: false

    }
  },
  computed: {
    recommendChannels () {
      const arr = []
      // 遍历所有频道
      this.allChannels.forEach(channel => {
        // 我的频道列表中是否包含当前遍历项

        // [{ id: 1, name: '推荐' }, { id: 2, name: 'Android' } ]
        // { id: 3: name: '哈哈' }

        // find 方法
        // 找到第1个满足 item.id === channel.id 条件的元素
        const ret = this.channels.find(item => {
          return item.id === channel.id
        })

        // 如果我的频道列表中不包含当前遍历的频道，那我就把它收集到 arr 中
        if (!ret) {
          arr.push(channel)
        }
      })

      return arr
    }
  },
  watch: {
    channels (newVal, oldVal) {
      setItem('channels', this.channels)
    }
  },
  created () {
    this.loadUserChannels()
  },
  methods: {
    onChannelActiveOrDelete (channel, index) {
      if (this.isEditShow && channel.name != '推荐') {
        // 编辑状态，执行删除操作
        this.channels.splice(index, 1)
      } else {
        // 非编辑状态，执行切换频道
        this.active = index
        this.isChannelShow = false
      }
    },
    onChannelAdd (channel) {
      // 将点击的频道项添加到我的频道列表中
      this.channels.push(channel)
      // 不需要删除，我的频道改变，计算属性 recommendChannels 重新调用求值
    },
    openChangeOpen () {
      console.log('open')
      getAllChannels({}).then(res => {
        console.log(res)

        const allChannels = res.data.data.channels
        allChannels.forEach(channel => {
          channel.articles = [] // 频道的文章列表
          channel.finished = false // 频道的加载结束状态
          channel.timestamp = null // 用于获取频道下一页数据的时间戳
        })
        this.allChannels = allChannels

        console.log(this.allChannels)
      })
    },
    onLoad () {
      // 获取当前频道
      // this.active 双向绑定了标签页组件，该数据正好对应频道的索引
      const activeChannel = this.channels[this.active]

      // 获取当前频道的文章列表
      const articles = activeChannel.articles

      // 1. 请求获取数据
      getArticles({
        channel_id: activeChannel.id, // 频道 id
        timestamp: activeChannel.timestamp || Date.now(), // 获取下一页数据的时间戳，Date.now() 表示获取当前最新数据
        with_top: 1
      }).then(res => {
        console.log('@@###', res)
        articles.push(...res.data.data.results)
        console.log('@@###', articles)
        this.loading = false
        const preTimestamp = res.data.data.pre_timestamp
        if (preTimestamp) {
          // 更新获取下一页数据的时间戳
          activeChannel.timestamp = preTimestamp
        } else {
          activeChannel.finished = true
        }
      })
    },

    onRefresh () {
      // 获取到当前的新闻频道
      const activeChannel = this.channels[this.active]
      // 1. 请求获取最新数据
      getArticles({
        channel_id: activeChannel.id,
        timestamp: Date.now(), // 获取最新数据传递当前最新时间戳即可
        with_top: 1
      }).then(res => {
        // 2. 把数据放到列表的顶部
        const articles = res.data.data.results
        activeChannel.articles.unshift(...articles)
        // 3. 停止下拉刷新的转圈圈
        this.isLoading = false

        // 4. 提示用户刷新成功
        const message = articles.length
          ? `更新了${articles.length}条数据`
          : '暂无数据更新'

        this.$toast(message)
      })
    },

    async loadUserChannels () {
      const localChannels = getItem('channels')
      if (localChannels) {
        this.channels = localChannels
      } else {
        await getUserChannels().then(res => {
          console.log(res)
          const channels = res.data.data.channels
          channels.forEach(channel => {
            channel.articles = [] // 频道的文章列表
            channel.finished = false // 频道的加载结束状态
          })
          this.channels = channels
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-button{
    width: 220px;
    background: #5babfb;
  }
.home {
  .article-info span {
    margin-right: 10px;
  }
  .van-tabs {
    position: relative;
    // 频道列表
    /deep/ .van-tabs__wrap {
      position: fixed;
      top: 46px;
      z-index: 2;
      right: 0;
      left: 0;
    }
    // 频道内容
    /deep/ .van-tabs__content {
      padding-top: 90px;
    }
    .van-icon-wap-nav {
      position:fixed;
      right: 0;
      align-items: center;
      background-color: #fff;
      opacity: 0.8;
      padding-top: 8px;
      font-size: 24px;
    }
  }
}
.channel-container {
  padding-top: 30px;
}
.close-icon{
  position: absolute;
  top: -23px;
  right: -49px;
}
</style>
